package cn.tedu.boot22.controller;

import cn.tedu.boot22.entity.Hero;
import cn.tedu.boot22.mapper.HeroMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Controller
public class HeroController {
    //此注解的作用: Spring框架结合Mybatis框架会自动将HeroMapper生成一个实现类和里面的方法
    //且会自动实例化该对象  required = false 告诉idea编译器此对象是非必须的
    //@Autowired(required = false)
    @Autowired
    HeroMapper mapper;

    @RequestMapping("/add")
    @ResponseBody
    public String add(Hero hero){
        System.out.println("hero = " + hero);
        //此方法相当于之前的JDBC代码
//        public String reg (User user){
//            try (Connection conn = DBUtils.getConn()){
//                String sql = "select id from user where username=?";
//                PreparedStatement ps = conn.prepareStatement(sql);
//                ps.setString(1,user.getUsername());
//                ResultSet rs = ps.executeQuery();
//                if(rs.next()){
//                    return "用户已存在!!!";
//                }
//                //2. 实现往user表中添加数据
//                String insertSql = "insert into user values(null,?,?,?)";
//                PreparedStatement insertPs = conn.prepareStatement(insertSql);
//                insertPs.setString(1, user.getUsername());
//                insertPs.setString(2, user.getPassword());
//                insertPs.setString(3, user.getNick());
//                insertPs.executeUpdate();
//
//            } catch (SQLException throwables) {
//                throwables.printStackTrace();
//            }
//            return "注册成功!!!";
//        }
        mapper.insert(hero);
        return "添加完成!!!";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(String name){
        mapper.deleteByName(name);
        return "删除完成!!!";
    }

    @RequestMapping("/update")
    @ResponseBody
    public String update(Hero hero){
        System.out.println("hero = " + hero);
        mapper.update(hero);
        return "修改完成!!!";
    }

    @RequestMapping("/select")
    @ResponseBody
    public String select(){
        List<Hero> list = mapper.select();
        return list.toString();
    }
}
